package edu.mit.simile.longwell.jfresnel;

import java.io.FileInputStream;
import java.net.URL;

import org.apache.log4j.Logger;
import com.hp.hpl.jena.rdf.model.Model;

import edu.mit.simile.longwell.LongwellServer;
import edu.mit.simile.longwell.LongwellServlet;
import fr.inria.jfresnel.Constants;
import fr.inria.jfresnel.FresnelDocument;
import fr.inria.jfresnel.jena.FresnelJenaParser;
import fr.inria.jfresnel.fsl.FSLHierarchyStore;
import fr.inria.jfresnel.fsl.jena.FSLJenaEvaluator;
import fr.inria.jfresnel.fsl.FSLNSResolver;
import fr.inria.jfresnel.sparql.SPARQLNSResolver;
import fr.inria.jfresnel.sparql.jena.SPARQLJenaEvaluator;


public class FresnelDoc {
	
	private String FRESNEL_DATA_FILE_PATH = LongwellServer.getFresnelPath();
	//"/home/nicola/workspace/Longwell2/WebContent/WEB-INF/conf/fresnel.n3";
	//private String urlFresnel = ClassLoader.getSystemResource("fresnel.n3").toString();
	
	private Model _model = null;
	
	private static FresnelDocument fd;
	
	FSLJenaEvaluator fje = null;
	
	FSLNSResolver fnsr = null; 
	SPARQLNSResolver snsr = null;
	FSLHierarchyStore fhs = null;
		
	final static private Logger s_logger =
			Logger.getLogger(FresnelDoc.class);
	
	public FresnelDoc(Model model){
		_model = model;
		

		/* Declare the namespace prefix bindings for the prefixes used in the model */
		fnsr = new FSLNSResolver(); 
		//fnsr.addPrefixBinding("riv", "http://www.semanticweb.org/ontologies/2011/9/Rivela-Flussi.owl#");
		snsr = new SPARQLNSResolver();
		
		/* Declare the RDFS and OWL files that should be loaded for RDFS/OWL awareness */
		fhs = new FSLHierarchyStore();
	}
	
	public FSLJenaEvaluator getFresnelEvaluator() {
		 
		/* Instantiate an evaluator */ 
		fje = new FSLJenaEvaluator(fnsr, fhs); 
		SPARQLJenaEvaluator sje = new SPARQLJenaEvaluator(snsr);
	 	
        
		fje.setModel(_model);
		sje.setModel(_model);
		
		return fje;
		
	}
	
	public FresnelDocument getFresnelDocument() throws Exception {
		
				
		// instantiate a Fresnel parser that will create lenses and formats to be applied on a Jena model
		FresnelJenaParser fp = new FresnelJenaParser(fnsr, fhs); 
		
		s_logger.info("Loading fresnel configuration file from "+ FRESNEL_DATA_FILE_PATH);
				
		try {
			if(fd==null){
				FileInputStream fstream = new FileInputStream(FRESNEL_DATA_FILE_PATH);
				fd = fp.parse(fstream, Constants.N3_READER, "");				
			}
		} catch (Exception e) {
			// was com.hp.hpl.jena.n3.N3Exception
			s_logger.info("Internal parsing error");
			throw new Exception("Internal parsing error");
		}
		
		return fd;
	}
}
